package com.clouddot.baipai.ui.fragment.H_MainFragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Base64;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.clouddot.baipai.R;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.infrastructure.environment.Environment;
import com.clouddot.baipai.model.TasksRepository;
import com.clouddot.baipai.model.beam.login.loginResponse;
import com.clouddot.baipai.model.beam.postPhoto.postPhotoResponse;
import com.clouddot.baipai.ui.activity.H_SMainActivity;
import com.clouddot.baipai.ui.activity.H_UMainActivity;
import com.clouddot.baipai.ui.fragment.BaseFragment;
import com.clouddot.baipai.ui.util.Preview.CameraPreview;
import com.clouddot.baipai.ui.util.ThreadPool.ThreadPool;
import com.clouddot.baipai.ui.util.ToastUtil;

import java.util.Map;

/**
 * Created by wxy on 2018/4/10.
 */

public class H_UScanFaceFragment extends BaseFragment{

    private View view;
    private Activity context;

    private Camera mCamera;
    private CameraPreview mPreview;
    private FrameLayout mCameralayout;
    private RelativeLayout mTakePictureBtn;

    private boolean isRunning = false;
    private Map<Integer, Pair<String, Integer>> columns;
    private H_UMainActivity activity;

    private boolean isFragment = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        activity = (H_UMainActivity) getActivity();
        isFragment = false;
        return view;
    }

    @Override
    protected void setContentView() {
        super.setContentView();
        if(Environment.getInstance().Height <= 100){
            view = LayoutInflater.from(context).inflate(R.layout.h_f_scanfacefg, null);

        }else{
            view = LayoutInflater.from(context).inflate(R.layout.v_f_scanfacefg,null);
        }
    }

    @SuppressLint("WrongViewCast")
    @Override
    protected void initControls() {
        super.initControls();
        mCameralayout = view.findViewById(R.id.camera_preview);
        mTakePictureBtn = view.findViewById(R.id.takePhoto);

    }

    @Override
    protected void setListener() {
        super.setListener();
        mTakePictureBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                H_SMainActivity.backTime = Env.getAppContext().backMainTime * 60;

                if(!isRunning){
                    isRunning = true;
                    mCamera.takePicture(null, null, mPictureCallback);

//                    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.demo);
//                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//
//                    bitmap.compress(Bitmap.CompressFormat.JPEG,90,outputStream );
//
//                    byte[] imagebyte = outputStream.toByteArray();
//
//                    photo = Base64.encodeToString(imagebyte, 0, imagebyte.length, Base64.DEFAULT);
//
//                    runThreadAction();
                }else{
                    ToastUtil.showToast(activity,"正在识别，不用再点击拍照按钮了");
                }
            }
        });

        Env.getAppPresenter().tasksRepository.setPostPhoto(new TasksRepository.postPhotoResult() {
            @Override
            public void success(final postPhotoResponse response) {
                Env.info(response.idno);
                Message msg = new Message();
                msg.what = 1;
                msg.obj = response.idno;
                handler.sendMessage(msg);
            }

            @Override
            public void failure(final postPhotoResponse response) {
                context.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mCamera.startPreview();
                        ToastUtil.showToast(context,response.getErrMsg());
                        isRunning = false;

                    }
                });


            }
        });

    }

    @Override
    public void onAttach(Activity context) {
        this.context = context;
        super.onAttach(context);
    }

    @Override
    public void onPause() {
        super.onPause();
        isFragment = true;
        releaseCamera();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!checkCameraHardware(context)) {
            ToastUtil.showToast(context, "相机不支持", Toast.LENGTH_SHORT);
        } else {
            openCamera();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void runThreadAction() {
        super.runThreadAction();
    }

    @Override
    protected Object runThreadActionExceute() {
        super.runThreadActionExceute();
        return Env.getAppPresenter().postPhoto(photo, "jpeg", "1", "1");

    }

    @Override
    protected void runThreadActionSuccess(Object result) {
        super.runThreadActionSuccess(result);
    }

    @Override
    protected void runThreadActionError(Exception ex) {
        super.runThreadActionError(ex);
    }


    @Override
    public void runThreadAction(String actionName) {
        super.runThreadAction(actionName);
    }

    @Override
    protected Object runThreadActionExceute(String actionName) {
        return Env.getAppPresenter().login(actionName);
    }

    @Override
    protected void runThreadActionSuccess(String actionName, Object result) {
        super.runThreadActionSuccess(actionName, result);
        isRunning = false;
        loginResponse response = (loginResponse) result;
        mCamera.startPreview();
        if(response.isSuccess()){
            ToastUtil.showToast(context,"识别通过");
            activity.selectLinear(5);
        }else{
            ToastUtil.showToast(context,"识别通过，平台未记录该身份信息");
        }
    }

    @Override
    protected void runThreadActionError(String actionName, Exception ex) {
        super.runThreadActionError(actionName, ex);
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    runThreadAction(msg.obj+"");
                    break;

                case 2:
                   handler.postDelayed(new Runnable() {
                       @Override
                       public void run() {
                           if(!isFragment) {
                               ToastUtil.showToast(context, "请对准摄像头");
                               handler.postDelayed(new Runnable() {
                                   @Override
                                   public void run() {
                                       mTakePictureBtn.performClick();
                                   }
                               }, 1000);
                           }
                       }
                   },3000);

                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 开始预览相机
     */
    @SuppressLint("ClickableViewAccessibility")
    public void openCamera() {
        if (mCamera == null) {
            ThreadPool.getInstance().execute(new Runnable() {
                @Override
                public void run() {
                    mCamera = getCameraInstance();
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mPreview = new CameraPreview(context, mCamera);
//                            mPreview.setRotation(180);
                            mCameralayout.addView(mPreview);
                        }
                    });
                    handler.sendEmptyMessage(2);
                }
            });


        }else{
            mPreview = new CameraPreview(context, mCamera);
            mCameralayout.addView(mPreview);
        }
    }

    /**
     * // 释放相机
     */
    public void releaseCamera() {
        if (mCamera != null) {
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
    }

    /**
     * 判断相机是否支持
     *
     * @param context
     * @return
     */
    private boolean checkCameraHardware(Context context) {
        if (context.getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取相机
     *
     * @return
     */
    public static Camera getCameraInstance() {
        Camera c = null;
        try {
            c = Camera.open();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return c;
    }

    private String photo;
    /**
     * 拍照回调
     */
    private Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
        @Override
        public void onPictureTaken(final byte[] data, Camera camera) {

            photo = Base64.encodeToString(data, 0, data.length, Base64.DEFAULT);
            runThreadAction();

        }
    };
}
